﻿/****************************** Module Header ******************************\
 * Module Name:  ProgramMutexHelper.cs
 * Module Version:  1.0.0 (2012-10-22)
 * Copyright (c) AnyEB.Com (14507247@qq.com)
 * 
 * This class is use for run a mutex program. 
 * 
 * This source is subject to the GPL License.
 * See http://www.gnu.org/licenses/gpl.html.
 * All other rights reserved.
 * 
 * THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND, 
 * EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED 
 * WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE.
\***************************************************************************/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;
using System.Diagnostics;
using System.Reflection;
using System.Windows.Forms;

namespace UCF.Core.Forms
{
    /// <summary>
    /// 程序单例运行
    /// </summary>
    public class ProgramMutexHelper
    {
        [DllImport("User32.dll")]
        private static extern bool ShowWindowAsync(IntPtr hWnd, int cmdShow);

        [DllImport("User32.dll")]
        private static extern bool SetForegroundWindow(IntPtr hWnd);

        private const int WS_SHOWNORMAL = 1;

        [DllImport("user32.dll")]
        private static extern int IsIconic(IntPtr hWnd);


        public static Process RunningInstance(Assembly currentAssem)
        {
            Process current = Process.GetCurrentProcess();
            Process[] processes = Process.GetProcessesByName(current.ProcessName);
            foreach (Process process in processes)
            {
                if (process.Id != current.Id)
                {
                    if (currentAssem.Location.Replace("/", "//") == current.MainModule.FileName)
                    {
                        return process;
                    }
                }
            }
            return null;
        }

        /// <summary> 
        /// 显示已运行的程序。 
        /// </summary> 
        public static void HandleRunningInstance(Process instance)
        {
            ShowWindowAsync(instance.MainWindowHandle, WS_SHOWNORMAL);
            SetForegroundWindow(instance.MainWindowHandle);
        }

        /// <summary>
        /// 检测是否有残余的进程
        /// <para>用于系统出错的时候，进程未正常关闭，启动新程序的时候无法正常打开界面</para>
        /// </summary>
        /// <param name="currentAssem"></param>
        /// <remarks>2014-3-28 by sutroon</remarks>
        public static void CheckExistThread(Assembly currentAssem)
        {
            Process current = Process.GetCurrentProcess();
            Process[] processes = Process.GetProcessesByName(current.ProcessName);
            List<Process> lstP = new List<Process>();
            foreach (Process process in processes)
            {
                if (process.Id != current.Id)
                {
                    if (currentAssem.Location.Replace("/", "//") == current.MainModule.FileName)
                    {
                        lstP.Add(process);
                    }
                }
            }
            if (lstP.Count==0) return;
            if (DialogResult.OK != MessageBox.Show(string.Format("发现已有 [{0}] 个相同的程序在后台运行,是否强制关闭较早的后台进程?",lstP.Count), "提示", MessageBoxButtons.OKCancel)) return;
            foreach (Process p in lstP)
            {
                p.Kill();
                System.Threading.Thread.Sleep(500);
            }
        }
    }
}
